//app.js
const apiBase = 'https://www.raverhub.cn/cardapi/'
App({
  onLaunch: function () {
    wx.getSetting({
      success: res => {
        console.log(res)
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          console.log(wx.getStorageSync('token'))
          if (wx.getStorageSync('token')==undefined||wx.getStorageSync('token')=='') {
            wx.setStorageSync('loginType', '1')
            wx.setStorageSync('userInfo', '')
          }else{
            wx.getUserInfo({
              success: res => {
                console.log(res)
                let data = {
                  encryptedData:res.encryptedData,
                  iv:res.iv
                }
                this.request('ugc/updateUnionid',data).then(item=>{
                  console.log(item)
                  wx.hideLoading()
                })
                // 可以将 res 发送给后台解码出 unionId
                this.globalData.userInfo = res.userInfo
                // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                // 所以此处加入 callback 以防止这种情况
                if (this.userInfoReadyCallback) {
                  this.userInfoReadyCallback(res)
                }
              }
            })
          }
        }
      }
    })
  },
  globalData: {
    userInfo: null,
    apiImgBase1:'https://raverhub-os.oss-cn-hangzhou.aliyuncs.com/',
    apiImgBase2:'https://raverhub-os.oss-cn-hangzhou.aliyuncs.com/wxapp/',
  },
  request:function(url, data, method){
    wx.showLoading({
      title: '加载中',
    })
    const headers = {}
    const token = wx.getStorageSync('token')
    headers["Authorization"] = token==''?'':"Bearer " + token;
    headers["content-type"] = "application/json";
    var promise = new Promise((resolve, reject) => {
       //init
       var that = this;
       var postData = data;
       /*
       //自动添加签名字段到postData，makeSign(obj)是一个自定义的生成签名字符串的函数
       postData.signature = that.makeSign(postData);
       */
       //网络请求
       wx.request({
          url:apiBase+url,
          data: postData,
          header:headers,
          method,
          success: function (res) {
            if(res.data.success){

            }else{
              if(res.data.status == '-10001'){
                wx.setStorageSync('userInfo', '')
                wx.setStorageSync('token', '')
                wx.setStorageSync('code', '')
              }else{

              }
            }
            resolve(res.data)
          },
          error: function (e) {
             reject('网络出错');
             wx.hideLoading()
          }
       })
    });
    return promise;
 },
})